//
//  WHEnterpriseCompanyVC.m
//  WHEasyBizLink
//
//  Created by shengmeng chen on 2024/11/29.
//

#import <WHWlproxy/WHKeyChainDataManager.h>
#import "WHEnterpriseCompanyVC.h"
#import "WHEnterpriseCompanyCell.h"
#import "WHEnterpriseCompanyModel.h"
#import "WHCompanyInfoApplyModel.h"
#import "WHCompanyInfoApplyVC.h"
#import "SearchTitleView.h"
#import "SDAutoLayout.h"
#import "WHTdsModel.h"
#import "MJRefresh.h"

#define pagesize 80

@interface WHEnterpriseCompanyVC ()

@property (nonatomic,strong)UIBarButtonItem *rightItem;
@property(nonatomic,assign)CGFloat historyY;
@property (nonatomic,assign)int  mPageIndex;
@property(nonatomic,strong)NSString*searchString;

@end

@implementation WHEnterpriseCompanyVC
- (void)viewDidLoad {
    self.mPageIndex = 1;
    self.searchString = @"";
    [super viewDidLoad];
    //self.view.backgroundColor =[UIColor whiteColor];
    self.navigationController.navigationBar.topItem.title = @"企业单位";
    
    // 1.注册通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationAction:) name:NOT_NAME_TDSCHANGE object:nil];
}

#pragma mark - loadDatas
- (void)loadDatas{
    [super loadDatas];
    [self getComListWithisdropDown:NO];
}

#pragma mark - setupUI
- (void)setupUI{
    [super setupUI];
    //一个简单的super setupUI = createTableView
    self.tableView.frame =CGRectMake(0,navHeight1+40,ScreenW,ScreenH-navHeight1-40);
    self.navigationItem.rightBarButtonItem =self.rightItem;
    

    self.view.layer.contents = (__bridge id _Nullable)([UIImage imageNamed:@"enterprise_bg"].CGImage);
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBar.subviews.firstObject.alpha = 0;
    
    self.searchView.backgroundColor =[UIColor clearColor];
    self.searchView.searchBar.backgroundColor =[UIColor whiteColor];
    self.tableView.backgroundColor =[UIColor clearColor];

}

-(void)rightBarButtonItemClicked
{
    WHCompanyInfoApplyVC*vc = [[WHCompanyInfoApplyVC alloc]init];
    vc.hidesBottomBarWhenPushed = YES;
    vc.type = WHInfoApplyTypeAdd;
    vc.registerSuccessBlock = ^(WHEnterpriseCompanyModel * _Nonnull model) {
        [self.datas insertObject:model atIndex:0];
        [self.tableView reloadData];
    };
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark 接收服务平台改变通知
-(void)notificationAction:(NSNotification *)notification{
    [self getComListWithisdropDown:NO];
}

#pragma mark - 查询公司列表
- (void)getComListWithisdropDown:(BOOL)isdropDown{
    NSDictionary *tds = [WHTdsModel getSelTDSProxyList];
    NSArray *allkey = [tds allKeys];
    if (allkey.count==0) {
        return;
    }
    
    NSMutableDictionary *dic = [NSMutableDictionary new];
    dic[@"currPage"]     = [NSString stringWithFormat:@"%d",self.mPageIndex];//self.comModel.id;
    dic[@"perPageCount"] = [NSString stringWithFormat:@"%d",pagesize];
    dic[@"udid"]         = kApp.userPhone;
    dic[@"conditions"]   = self.searchString;
    dic[@"proxy"]        = tds[@"url"];
    dic[@"target"]       = tds[@"TDSid"];

    [WHEnterpriseCompanyModel  qryListCompanyWithFromdata:dic succesefulBlock:^(id  _Nonnull responseObject) {
        NSArray *dataList = (NSArray*)responseObject;
        
        if (dataList.count < pagesize){
            //拿到当前的小于Request_count时，表示没有更多的数据了
            [self setViewFooterWithHave:NO];
        }else{
            [self setViewFooterWithHave:YES];
            // 拿到当前的不小于Request_count时，表还有更多的数据了
            [self setViewFooterEndRefresh];
        }
        
        NSMutableArray *mutabelArray;
        if(isdropDown){
            [self.datas addObjectsFromArray:dataList];
            mutabelArray = self.datas;
        }else{
            mutabelArray = [NSMutableArray arrayWithArray:dataList];
        }
        self.datas =[NSMutableArray arrayWithArray:mutabelArray];
    } andFailureBlock:^(NSString * _Nonnull error) {
        NSLog(@"WHEnterpriseCompanyVC---查询单位列表失败：%@",error);
        self.datas = [NSMutableArray new];
    }];
}

#pragma mark 下拉刷新开始
- (void)dropDownRefresh
{
    if(!self.tableView.mj_footer) return;
    self.mPageIndex++;
    [self getComListWithisdropDown:YES];
}

- (void)setViewFooterWithHave:(BOOL) have{
    if(have){
        self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            [self dropDownRefresh];
        }];
    }else{
        self.tableView.mj_footer =nil;
    }
}

- (void)setViewFooterEndRefresh{
    [self.tableView.mj_footer endRefreshing];
}

#pragma mark - <searchViewDelegate>
-(void)searchTileViewTextFieldDidChange:(NSString*)textFieldString
{
    if (textFieldString.length==0)
    {
        self.mPageIndex = 1;
        self.searchString     = @"";
        [self.datas removeAllObjects];
        [self.tableView reloadData];
        [self.tableView.mj_footer endRefreshing];
        [self getComListWithisdropDown:NO];
    }
}

//点击搜索调用
-(void)searchTileViewSearchButtonClickSearchString:(NSString *)searchString
{
    self.searchString = searchString;
    self.mPageIndex = 1;
    [self.datas removeAllObjects];
    [self.tableView reloadData];
    [self.tableView.mj_footer endRefreshing];
    [self getComListWithisdropDown:NO];
}

#pragma mark - <tableViewDelegate>
- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath{
   
    WHEnterpriseCompanyCell *cell = [WHEnterpriseCompanyCell
                                     createReuseIdentifier:@"WHEnterpriseCompanyCellID" WithTableView:tableView];
    cell.model = self.datas[indexPath.row];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView
 heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    return [tableView cellHeightForIndexPath:indexPath model:self.datas[indexPath.row] keyPath:@"model" cellClass:[WHEnterpriseCompanyCell class] contentViewWidth:ScreenW];
    //return kMarginH*16;
}

-(void)tableView:(UITableView *)tableView
commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
forRowAtIndexPath:(NSIndexPath *)indexPath
{
   
}


- (UISwipeActionsConfiguration *)tableView:(UITableView *)tableView trailingSwipeActionsConfigurationForRowAtIndexPath:(NSIndexPath *)indexPath {
    WHEnterpriseCompanyModel*model = self.datas[indexPath.row];
    NSDictionary *dict =  [WHTdsModel getSelTDSProxyList];
    UIContextualAction *deleteAction = [UIContextualAction contextualActionWithStyle:UIContextualActionStyleDestructive
                                                                       title:@""
                                                                       handler:^(UIContextualAction * _Nonnull action, __kindof UIView * _Nonnull sourceView, void (^ _Nonnull completionHandler)(BOOL)) {
        // 处理删除操作
        // 例如，从数据源中移除对应的元素，并调用tableView的deleteRowsAtIndexPaths方法
        // 这里仅作示例，不展示完整的数据源修改和UI更新代码
        NSLog(@"Delete action triggered for row %ld", (long)indexPath.row);
       
        UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"是否确定要删除" message:@"" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancelAtcion =[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        }];
        UIAlertAction *suretcion =[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            
            [WHInfoModel setCompanyInfo:model.comid withTSD:dict withopertype:WHComTypeDele withBlock:^(id  _Nonnull responseObject) {
                
                [self.datas removeObjectAtIndex:indexPath.row];
                [self.tableView reloadData];
            } failureBlock:^(NSString * _Nonnull msg) {
            }];
        
        }];
        [alertC addAction:cancelAtcion];
        [alertC addAction:suretcion];
        
        [self presentViewController:alertC animated:YES completion:nil];
        completionHandler(YES); // 通知系统已完成操作
    }];

    // 设置删除操作的图标
    deleteAction.backgroundColor = [UIColor whiteColor];
    deleteAction.image = [UIImage imageNamed:@"enterprise_delete"];
    
    UIContextualAction *mdfAction = [UIContextualAction contextualActionWithStyle:UIContextualActionStyleDestructive
                                                                       title:@""
                                                                       handler:^(UIContextualAction * _Nonnull action, __kindof UIView * _Nonnull sourceView, void (^ _Nonnull completionHandler)(BOOL)) {
        
        WHCompanyInfoApplyVC*vc = [[WHCompanyInfoApplyVC alloc]init];
        vc.type = WHInfoApplyTypeMDF;
        vc.model = model;
        vc.hidesBottomBarWhenPushed = YES;
        vc.modifySuccessBlock = ^(WHEnterpriseCompanyModel * _Nonnull model) {
           
            [self.datas removeObjectAtIndex:indexPath.row];
            [self.datas insertObject:model atIndex:indexPath.row];
            [self.tableView reloadData];
        };
        [self.navigationController pushViewController:vc animated:YES];
        
        completionHandler(YES); // 通知系统已完成操作
    }];

    // 设置修改操作的图标
    mdfAction.backgroundColor = [UIColor whiteColor];
    mdfAction.image = [UIImage imageNamed:@"enterprise_modify"];
    
    NSString *title       = @"停用";
    NSString *alertString = @"是否确定要停用";
    NSString *alertimg = @"enterprise_stop";
    if ([model.enable isEqualToString:@"0"]) {
                  title = @"启用";
        alertString     = @"是否确定要启用";
        alertimg = @"enterprise_start";
    }
    
    UIContextualAction *action0 =[UIContextualAction contextualActionWithStyle:UIContextualActionStyleNormal title:@"" handler:^(UIContextualAction * _Nonnull action, __kindof UIView * _Nonnull sourceView, void (^ _Nonnull completionHandler)(BOOL)) {
        
        UIAlertController *alertC = [UIAlertController alertControllerWithTitle:alertString message:@"" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancelAtcion =[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        }];
        UIAlertAction *suretcion =[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            [WHInfoModel setCompanyInfo:model.comid withTSD:dict withopertype:WHComTypeEnable withBlock:^(id  _Nonnull responseObject) {
                
                if([model.enable isEqualToString:@"0"]){
                    model.enable = @"1";
                }else{
                    model.enable = @"0";
                }
                [tableView reloadData];
            } failureBlock:^(NSString * _Nonnull msg) {
            }];
            
        }];
        [alertC addAction:cancelAtcion];
        [alertC addAction:suretcion];
        [self presentViewController:alertC animated:YES completion:nil];
       
        completionHandler(YES);
    }];

    action0.backgroundColor = [UIColor whiteColor];
    action0.image = [UIImage imageNamed:alertimg];
 
    
    // 创建UISwipeActionsConfiguration对象并添加操作
    UISwipeActionsConfiguration *configuration = [UISwipeActionsConfiguration configurationWithActions:@[deleteAction,mdfAction,action0]];
    return configuration;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    WHEnterpriseCompanyModel*model = self.datas[indexPath.row];
    DebugLog(@"tableView = %ld",(long)indexPath.row);
    WHCompanyInfoApplyVC*vc = [[WHCompanyInfoApplyVC alloc]init];
    vc.type = WHInfoApplyTypeMDF;
    vc.model = model;
    vc.hidesBottomBarWhenPushed = YES;
    vc.modifySuccessBlock = ^(WHEnterpriseCompanyModel * _Nonnull model) {
       
        [self.datas removeObjectAtIndex:indexPath.row];
        [self.datas insertObject:model atIndex:indexPath.row];
        [self.tableView reloadData];
    };
    [self.navigationController pushViewController:vc animated:YES];
}
-(void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView
{
    [self.view endEditing:YES];
}

//设置滑动的判定范围
- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset
{
    if (self.historyY+20<targetContentOffset->y)
    {
        [self setTabBarHidden:YES];
    }
    else if(self.historyY-20>targetContentOffset->y)
    {
        [self setTabBarHidden:NO];
    }
    self.historyY=targetContentOffset->y;
}

#pragma mark 隐藏显示tabbar
- (void)setTabBarHidden:(BOOL)hidden
{
    UIView *tab = self.tabBarController.view;
    CGRect  tabRect=self.tabBarController.tabBar.frame;
    if ([tab.subviews count] < 2) {
        return;
    }

    UIView *view;
    if ([[tab.subviews objectAtIndex:0] isKindOfClass:[UITabBar class]]) {
        view = [tab.subviews objectAtIndex:1];
    } else {
        view = [tab.subviews objectAtIndex:0];
    }

    if (hidden) {
        view.frame = tab.bounds;
        tabRect.origin.y=[[UIScreen mainScreen] bounds].size.height+self.tabBarController.tabBar.frame.size.height;
    } else {
        view.frame = CGRectMake(tab.bounds.origin.x, tab.bounds.origin.y, tab.bounds.size.width, tab.bounds.size.height);
        tabRect.origin.y=[[UIScreen mainScreen] bounds].size.height-self.tabBarController.tabBar.frame.size.height;
    }

    [UIView animateWithDuration:0.5f animations:^{
        self.tabBarController.tabBar.frame=tabRect;
    }completion:^(BOOL finished) {
    
    }];

}

-(UIBarButtonItem *)rightItem
{
    if (!_rightItem)
    {
        UIButton* rightBtn= [[UIButton alloc] initWithFrame:CGRectMake(0,0,25,25)];
      [rightBtn addTarget:self action:@selector(rightBarButtonItemClicked)forControlEvents:UIControlEventTouchUpInside];
        [rightBtn setBackgroundImage:[UIImage imageNamed:@"enterprise_add"] forState:UIControlStateNormal];
        _rightItem =[[UIBarButtonItem alloc]initWithCustomView:rightBtn];
    }
    return _rightItem;
}

@end
